<template>
  <div class="edit-page-wrap">
    <Head title="活动信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          class="edit-form-wrap"
        >
          <el-form-item label="活动名称" prop="name">
            <el-input
              v-model.trim="ruleForm.name"
              placeholder="请输入活动名称"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="活动日期" prop="dates">
            <div class="edit-date-wrap">
              <el-date-picker
                v-model="ruleForm.dates"
                popper-class="qc-date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                valueFormat="YYYY-MM-DD"
                format="YYYY-MM-DD"
                :disabled-date="disabledDate"
              />
            </div>
          </el-form-item>
          <el-form-item label="活动说明" prop="introduce">
            <el-input
              v-model.trim="ruleForm.introduce"
              placeholder="请输入活动说明"
              maxlength="200"
              type="textarea"
              :rows="3"
              show-word-limit
              clearable
            />
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <Head title="活动奖励">
      <template #content>
        <ComCoupon
          ref="comCouponRef"
          :activityId="id"
          :labelWidth="80"
        ></ComCoupon>
      </template>
    </Head>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import Head from '@/components/head/index.vue';
import ComCoupon from '../comCoupon.vue';
import { FormInstance, FormRules } from 'element-plus';
import {
  saveUserActivity,
  updateUserActivity,
  getUserActivityById,
} from '@/service/apis/market';

const router = useRouter();
const route = useRoute();
const {
  query: { id },
} = route;

const ruleFormRef = ref<FormInstance>();
const comCouponRef = ref();

const ruleForm = reactive({
  name: '', // 优惠券名称

  dates: [] as any, // 活动日期
  // startTime: '', // 活动开始时间
  // endTime: '', // 活动结束时间

  introduce: '', //活动说明
});

const disabledDate = (time: any) => {
  return time.getTime() < new Date(new Date().toLocaleDateString()).getTime();
};
// const checkTime = (rule: any, value: any, callback: any) => {
//   if (
//     new Date(value[1]).getTime() <
//     new Date(
//       new Date(new Date().getTime() + 24 * 60 * 60 * 1000).toLocaleDateString()
//     ).getTime()
//   ) {
//     callback(new Error('结束时间不能小于当前时间'));
//   }
//   callback();
// };
const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
  dates: [
    { required: true, message: '请选择活动日期', trigger: ['blur', 'change'] },
    // { validator: checkTime, trigger: ['blur', 'change'] },
  ],
  introduce: [{ required: true, message: '请输入活动说明', trigger: 'blur' }],
});

if (id) {
  getUserActivityById(id).then((res: any) => {
    if (res) {
      ruleForm.name = res.name;
      ruleForm.introduce = res.introduce;
      ruleForm.dates = [res.startTime, res.endTime];

      comCouponRef.value?.setData(res.detailMap[0]);
    }
  });
}

const back = () => {
  router.go(-1);
};

const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  if (!ruleFormRef.value) return;
  let flag = true;
  let objError = {} as any;
  let comData = [] as any;
  try {
    comData = await Promise.all([
      ruleFormRef.value.validate((e: any, fields: any) => {
        flag = flag ? e : false;
        if (!e) {
          objError = { ...objError, ...fields };
        }
      }),
      comCouponRef.value?.getData(),
    ]);
  } catch (e) {}
  if (!flag || !comData[1]) {
    for (const key in ruleForm) {
      if (objError[key]) {
        ruleFormRef.value.scrollToField(key);
        break;
      }
    }
    return;
  }

  const form: any = {
    type: 1,
    name: ruleForm.name,
    startTime: ruleForm.dates[0],
    endTime: ruleForm.dates[1],
    introduce: ruleForm.introduce,
    detailMap: { 0: comData[1] },
    participatingCount: 1,
    qualifiedType: 0,
    stationType: 0,
    targetType: 0,
  };

  console.log('form---', form, comData);
  if (id) {
    form.id = id;
    updateUserActivity(form).then((res: any) => {
      emit('clear-cache');
      back();
    });
  } else {
    saveUserActivity(form).then((res: any) => {
      emit('clear-cache');
      back();
    });
  }
};
</script>